import { Http, Headers, Response,Jsonp, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { Injectable } from '@angular/core';

import { Carrier } from './carrier';
import { SERVER } from '../../app.config';

@Injectable()
export class CarrierService {
    constructor(private http: Http){
    }

    getCarriers(): Promise<Carrier[]> {
        return this.http.get(SERVER.CARRIER)
        .toPromise()
        .then(response => response.json() as Carrier[])
        .catch(this.handleError);
    }

    getCarrier(carrier_id: number) {
        return this.getCarriers()
            .then(carriers => carriers.find(carrier => carrier.carrier_id ===carrier_id ));
    }

    private handleError(error: any): Promise<any> {
        console.error('错误：', error);

        return Promise.reject(error.message || error);
    }

    //添加
    private post(carrier: Carrier): Promise<Carrier> {
        let headers = new Headers({
            'Content-type': 'application/json'});

        return this.http.post(SERVER.CARRIER, JSON.stringify(carrier), {headers: headers})
        .toPromise()
        // .then(res => res.json().data)
        .catch(this.handleError);
    }

    //更新
    private put(carrier: Carrier): Promise<Carrier> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.CARRIER}` + '/'+ carrier.carrier_id;

        return this.http.put(url, JSON.stringify(carrier), {headers: headers})
                   .toPromise()
                   .then(() => carrier)
                   .catch(this.handleError);
    }

    //删除
    delete(carrier: Carrier): Promise<Response> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.CARRIER}/${carrier.carrier_id}`;

        return this.http
                   .delete(url, { headers: headers})
                   .toPromise()
                   .catch(this.handleError);
    }

    //保存
    save(carrier: Carrier): Promise<Carrier> {
        if (carrier.carrier_id) {
            return this.put(carrier)
        }
        return this.post(carrier);
    }
}
